{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 文件夹重命名"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "def delete_empty_folders(path):\n",
    "    # 检查路径是否存在\n",
    "    if not os.path.exists(path):\n",
    "        print(f\"路径 {path} 不存在。\")\n",
    "        return\n",
    "\n",
    "    # 检查路径是否是文件夹\n",
    "    if not os.path.isdir(path):\n",
    "        print(f\"{path} 不是一个文件夹。\")\n",
    "        return\n",
    "\n",
    "    # 获取路径中的所有文件和文件夹\n",
    "    with os.scandir(path) as entries:\n",
    "        for entry in entries:\n",
    "            # 构建完整的文件/文件夹路径\n",
    "            full_path = entry.path\n",
    "\n",
    "            # 如果是文件夹，递归地检查和删除空文件夹\n",
    "            if entry.is_dir():\n",
    "                new_name = entry.name + 'replace_str'\n",
    "                # 获取新文件夹的完整路径\n",
    "                new_full_path = os.path.join(current_dir, new_name)\n",
    "                # 重命名文件夹\n",
    "                os.rename(full_path, new_full_path)\n",
    "                \n",
    "\n",
    "# 设置目录\n",
    "current_dir =''\n",
    "delete_empty_folders(current_dir)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 获取文件夹名称"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "def delete_empty_folders(path):\n",
    "    # 检查路径是否存在\n",
    "    if not os.path.exists(path):\n",
    "        print(f\"路径 {path} 不存在。\")\n",
    "        return\n",
    "\n",
    "    # 检查路径是否是文件夹\n",
    "    if not os.path.isdir(path):\n",
    "        print(f\"{path} 不是一个文件夹。\")\n",
    "        return\n",
    "\n",
    "    # 获取路径中的所有文件和文件夹\n",
    "    with os.scandir(path) as entries:\n",
    "        for entry in entries:\n",
    "            # 如果是文件夹，递归地检查和删除空文件夹\n",
    "            if entry.is_dir():\n",
    "                print(entry.name+',')\n",
    "                \n",
    "\n",
    "# 设置目录\n",
    "current_dir =''\n",
    "delete_empty_folders(current_dir)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 根据关键字替换"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import re\n",
    "\n",
    "def rename_folders_containing_replace_str(root_dir, replace_str):\n",
    "    \"\"\"\n",
    "    递归遍历目录，重命名所有包含'replace_str'的文件夹\n",
    "    \"\"\"\n",
    "    for foldername, subfolders, filenames in os.walk(root_dir, topdown=False):\n",
    "        try:\n",
    "            if replace_str in foldername:\n",
    "                # 获取父目录和当前文件夹名\n",
    "                parent_dir = os.path.dirname(foldername)\n",
    "                current_name = os.path.basename(foldername)\n",
    "                \n",
    "                # 创建新名称（删除'replace_str'）\n",
    "                new_name = current_name.replace(replace_str, '')\n",
    "                new_name = new_name.strip()  # 去除可能的空格\n",
    "                \n",
    "                # 如果新名称为空，则跳过（避免创建空名称文件夹）\n",
    "                if not new_name:\n",
    "                    continue\n",
    "                \n",
    "                # 构建完整的新路径\n",
    "                new_path = os.path.join(parent_dir, new_name)\n",
    "                \n",
    "                # 避免重复或冲突\n",
    "                if new_path != foldername and not os.path.exists(new_path):\n",
    "                    os.rename(foldername, new_path)\n",
    "                    print(f'Renamed: \"{foldername}\" -> \"{new_path}\"')\n",
    "        except PermissionError:\n",
    "            print(f'Permission denied: {foldername}')\n",
    "        except Exception as e:\n",
    "            print(f'Error processing {foldername}: {str(e)}')\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    root_dir = ''  # 设置要处理的根目录\n",
    "    replace_str = ''\n",
    "    rename_folders_containing_replace_str(root_dir,replace_str)\n",
    "    print(\"处理完成。\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 为Windows下所有文件夹名称添加指定字符串"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "def add_string_to_subfolders(root_dir, add_string, position='suffix'):\n",
    "    \"\"\"\n",
    "    递归遍历目录，为所有子文件夹名称添加指定字符串（不包括根目录）\n",
    "    \n",
    "    参数:\n",
    "        root_dir: 要遍历的根目录（不会被重命名）\n",
    "        add_string: 要添加的字符串\n",
    "        position: 'prefix'表示添加到名称前，'suffix'表示添加到名称后\n",
    "    \"\"\"\n",
    "    \n",
    "    # 然后递归处理所有子文件夹（使用walk确保处理所有层级）\n",
    "    for foldername, subfolders, filenames in os.walk(root_dir):\n",
    "        for subfolder in subfolders:\n",
    "            subfolder_path = os.path.join(foldername, subfolder)\n",
    "            try:\n",
    "                # 获取父目录和当前文件夹名\n",
    "                parent_dir = os.path.dirname(subfolder_path)\n",
    "                current_name = os.path.basename(subfolder_path)\n",
    "                \n",
    "                # 根据位置参数构建新名称\n",
    "                if position == 'prefix':\n",
    "                    new_name = f\"{add_string}{current_name}\"\n",
    "                elif position == 'suffix':\n",
    "                    new_name = f\"{current_name}{add_string}\"\n",
    "                else:\n",
    "                    new_name = f\"{current_name}{add_string}\"\n",
    "                \n",
    "                # 构建完整的新路径\n",
    "                new_path = os.path.join(parent_dir, new_name)\n",
    "                \n",
    "                # 避免重命名为自身或路径已存在\n",
    "                if new_path != subfolder_path and not os.path.exists(new_path):\n",
    "                    os.rename(subfolder_path, new_path)\n",
    "                    print(f'Renamed: \"{subfolder_path}\" -> \"{new_path}\"')\n",
    "            except PermissionError:\n",
    "                print(f'权限不足: {subfolder_path}')\n",
    "            except Exception as e:\n",
    "                print(f'处理 {subfolder_path} 时出错: {str(e)}')\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    # 用户配置\n",
    "    directory = ''  # 要处理的根目录（不会被重命名）\n",
    "    string_to_add = ''         # 要添加的字符串\n",
    "    pos = 'suffix'                # 'prefix'或'suffix'\n",
    "    \n",
    "    add_string_to_subfolders(directory, string_to_add, pos)\n",
    "    print(\"\\n处理完成。\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "torch",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
